<template>
  <div class="system-dic-dialog-container">
    <el-dialog v-model="visible" destroy-on-close :title="dataForm.id ? $t('common.editBtn') : $t('common.addBtn')" width="80%">
      <el-form ref="dicDialogFormRef" :model="dataForm" label-width="90px" :rules="dataRules" v-loading="loading">
        <el-form-item :label="$t('dictItem.dictType')" prop="dictType">
          <el-input v-model="dataForm.dictType" clearable disabled
                    :placeholder="$t('dictItem.inputDictTypeTip')"></el-input>
        </el-form-item>
       
        <el-form-item  :label="$t('dictItem.label')" prop="label">
          <el-input type="textarea" v-model="dataForm.label" :placeholder="$t('dictItem.inputLabelTip')" clearable></el-input>
        </el-form-item>
        <el-form-item  :label="$t('dictItem.itemValue')" prop="value">
          <el-input type="textarea" v-model="dataForm.value" :placeholder="$t('dictItem.inputItemValueTip')" clearable></el-input>
        </el-form-item>
        <el-form-item   :label="$t('dictItem.description')" prop="description">
          <el-input type="textarea" v-model="dataForm.description" :placeholder="$t('dictItem.inputDescriptionTip')"
                    clearable></el-input>
        </el-form-item>
        <el-button   @click="onCreateItem()" type="primary" :disabled="loading">生成选项</el-button>  

        <!-- <div v-for="(item, index) in dictItemDataList">
          <el-input v-model="dictItemDataList[index].label" ></el-input>
          <el-input  ></el-input>
          <el-input ></el-input>
        </div> -->

        <el-table
			:data="dictItemDataList"
			style="width: 100%"
			border
		>
			<el-table-column prop="label" label="标签" show-overflow-tooltip><template #default="scope"><el-input v-model="dictItemDataList[scope.$index].label" ></el-input></template></el-table-column>
			<el-table-column prop="value" label="数据值"  show-overflow-tooltip><template #default="scope"><el-input v-model="dictItemDataList[scope.$index].value" ></el-input></template></el-table-column>
			<el-table-column prop="description" label="描述"  show-overflow-tooltip><template #default="scope"><el-input v-model="dictItemDataList[scope.$index].description" ></el-input></template></el-table-column>
			<el-table-column prop="sort" label="排序" show-overflow-tooltip><template #default="scope"><el-input v-model="dictItemDataList[scope.$index].sortOrder" ></el-input></template></el-table-column>
		</el-table>
       
        <!-- <el-form-item :label="$t('dictItem.sortOrder')" prop="sortOrder">
          <el-input-number v-model="dataForm.sortOrder" :placeholder="$t('dictItem.inputSortOrderTip')"
                           clearable></el-input-number>
        </el-form-item>
        <el-form-item :label="$t('dictItem.remarks')" prop="remarks">
          <el-input v-model="dataForm.remarks" type="textarea" rows="3" :placeholder="$t('dictItem.inputRemarksTip')"
                    maxlength="150"></el-input>
        </el-form-item> -->
      </el-form>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="visible = false">{{ $t('common.cancelButtonText') }}</el-button>
					<el-button type="primary" @click="onSubmit(false)" :disabled="loading">{{
              $t('common.confirmButtonText')
            }}</el-button>
           
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="dict-item-form">
import {useI18n} from 'vue-i18n';
import {getItemObj, addItemObj,addBatchItemObj, putItemObj, validateDictItemLabel} from '/@/api/admin/dict';
import {useMessage} from '/@/hooks/message';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const {t} = useI18n();

// 定义变量内容
const dicDialogFormRef = ref();

const visible = ref(false);
const loading = ref(false);
const dictItemDataList= ref([]);

const dataForm = reactive({
  id: '',
  dictId: '',
  dictType: '',
  value: '',
  label: '',
  itemList:[],
  description: '',
  sortOrder: 0,
  remarks: '',
});

const dataRules = reactive({
  value: [{required: true, message: '数据值不能为空', trigger: 'blur'}],
  label: [
    {required: true, message: '标签不能为空', trigger: 'blur'},
    {
      validator: (rule: any, value: any, callback: any) => {
        validateDictItemLabel(rule, value, callback, dataForm.dictType, dataForm.id !== '');
      },
      trigger: 'blur',
    },
  ],
  //description: [{required: true, message: '描述不能为空', trigger: 'blur'}],
  //sortOrder: [{required: true, message: '排序不能为空', trigger: 'blur'}],
});

const onCreateItem = ()=>{
    if(dataForm.label==''){
        useMessage().error("请输入标签项");
        return;
    }
    if(dataForm.value==''){
        useMessage().error("请输入数据值");
        return;
    }
    let labels=dataForm.label.replaceAll('，',',').split(',');
    let values=dataForm.value.replaceAll('，',',').split(',');
    let descriptions=dataForm.description.replaceAll('，',',').split(',');
    if(labels.length!=values.length){
        useMessage().error("标签项与数据值项个数不匹配");
        return;
    }
    dictItemDataList.value=[];
    labels.forEach(function(item,index){
        let sort=(index+1)*10;
        return dictItemDataList.value.push({ 
          "label": item,
        "dictId":dataForm.dictId,
        "dictType":dataForm.dictType, 
        "value": values[index], 
        "description": descriptions[index]?descriptions[index]:item,
         "sortOrder": sort 
        });
    })
    //dictItemDataList.value.push({"label":})

    
    console.log("labels:",labels,"values:",values,"descriptions:",descriptions);
}

// 打开弹窗
const openDialog = (row: any, dictForm: any) => {
  visible.value = true;
  dataForm.id = '';
  dataForm.label='';
  dataForm.value='';
  dataForm.itemList=[];

  nextTick(() => {
    dicDialogFormRef.value?.resetFields();
  });

  if (row?.id) {
    getItemObj(row.id).then((res) => {
      Object.assign(dataForm, res.data);
    });
  } else if (dictForm) {
    dataForm.dictId = dictForm.dictId;
    dataForm.dictType = dictForm.dictType;
  }
};

// 提交
const onSubmit = async (continueFlag:Boolean) => {
  const valid = await dicDialogFormRef.value.validate().catch(() => {
  });
  if (!valid) return false;
  if(dictItemDataList.value.length==0){
       useMessage().error("请输入选项");
        return;
  }
  try {
    loading.value = true;
    dataForm.itemList=dictItemDataList;
    dataForm.id ? await putItemObj(dataForm) : await addBatchItemObj(dataForm);
    useMessage().success(t(dataForm.id ? 'common.editSuccessText' : 'common.addSuccessText'));
    if(!continueFlag) visible.value = false;
    emit('refresh');
  } catch (err: any) {
    useMessage().error(err.msg);
  } finally {
    loading.value = false;
  }
};

// 暴露变量
defineExpose({
  openDialog,
});
</script>
<style scoped>
.form-row{ 
    display: flex;
}
</style>
